<template>
  <div class="app-container">
    <div class="search-bar">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item label="申请用户" prop="username">
          <el-input v-model="queryParams.username" placeholder="用户名"></el-input>
        </el-form-item>
        <el-form-item label="回收机构" prop="orgName">
          <el-input v-model="queryParams.orgName" placeholder="机构名称"></el-input>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="queryParams.status" class="!w-[200px]" clearable placeholder="全部" multiple collapse-tags
            :max-collapse-tags="2">
            <el-option v-for="item in RecycleStatusOptions" :value="item.value" :label="item.label"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="预期收益">
          <el-input-number v-model="queryParams.minExpectReturn" :precision="2" controls-position="right"
            placeholder="0.00">
            <template #suffix>
              <span>元</span>
            </template>
          </el-input-number>
          <span style="margin: 0 5px">至</span>
          <el-input-number v-model="queryParams.maxExpectReturn" :precision="2" controls-position="right"
            placeholder="0.00">
            <template #suffix>
              <span>元</span>
            </template>
          </el-input-number>
        </el-form-item>
        <el-form-item label="预约时间">
          <el-date-picker v-model="recycleTimeRange" type="datetimerange" range-separator="~" start-placeholder="开始时间"
            end-placeholder="结束时间" value-format="YYYY-MM-DD HH:mm:ss" format="YYYY-MM-DD HH:mm:ss" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">
            <template #icon>
              <Search />
            </template>
            搜索
          </el-button>
          <el-button @click="handleResetQuery">
            <template #icon>
              <Refresh />
            </template>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never">
      <el-table ref="dataTableRef" v-loading="loading" :data="pageData" highlight-current-row border>
        <el-table-column key="id" label="编号" prop="id" min-width="100" align="center" />
        <el-table-column key="username" label="申请用户" prop="username" min-width="100" align="center" />
        <el-table-column key="orgName" label="回收机构" prop="orgName" min-width="150" align="center" />
        <el-table-column key="mobile" label="联系方式" prop="mobile" min-width="150" align="center" />
        <el-table-column label="用户地址" min-width="250" align="center">
          <template #default="scope">
            <el-text class="w-250px mb-2" truncated>
              {{ assembleAddress(scope.row) }}
            </el-text>
          </template>
        </el-table-column>
        <el-table-column key="recycleTime" label="预约时间" prop="recycleTime" min-width="180" align="center" />
        <el-table-column key="expectReturn" label="期望收益(元)" prop="expectReturn" min-width="150" align="center" />
        <el-table-column key="status" label="状态" prop="status" min-width="150" align="center">
          <template #default="scope">
            <el-tag :type="RecycleStatusOptions.find((item) => item.value === scope.row.status)?.type">
              {{RecycleStatusOptions.find((item) => item.value === scope.row.status)?.label}}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column key="rejectReason" label="驳回原因" prop="rejectReason" min-width="150" align="center">
          <template #default="scope">
            <el-text class="w-250px mb-2" truncated>
              {{ scope.row.rejectReason }}
            </el-text>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="220">
          <template #default="scope">
            <el-button type="primary" size="small" link icon="Document" @click="handleOpenDialog('info', scope.row.id)"
              v-if="scope.row.status != '0'">详情</el-button>
            <el-button type="primary" size="small" link icon="Edit" @click="handleOpenDialog('audit', scope.row.id)"
              v-if="scope.row.status == '0' || scope.row.status == '2' || scope.row.status == '5'">审核</el-button>
            <!--处理记录-->
            <el-button type="primary" size="small" link icon="Files"
              v-if="scope.row.status == '3' || scope.row.status == '9'"
              @click.stop="openHistoryRecord(scope.row.id)">处理记录</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-if="total > 0" v-model:total="total" v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize" @pagination="handleQuery()" />
    </el-card>

    <!-- 回收请求主表单弹窗 -->
    <el-dialog v-model="dialog.visible" :title="dialog.title" width="700px" @close="handleCloseDialog"
      style="padding: 10px 20px" align-center>
      <!--主信息表单-->
      <el-form ref="dataFormRef" :model="formData" :rules="rules" label-width="100px">
        <el-form-item label="垃圾列表" v-if="formData.status && formData.status != '0' && formData.status != '1'">
          <div style="display: flex; flex-direction: column">
            <el-scrollbar max-height="200px">
              <!--垃圾列表（图片、类型、重量）-->
              <el-space fill style="margin-bottom: 10px">
                <div v-for="(waste, index) in formData.wasteList" :key="index">
                  <el-space>
                    <!-- 图片预览 -->
                    <el-image :zoom-rate="1.2" :max-scale="7" :min-scale="0.2" :preview-src-list="[waste.fileUrl]"
                      style="width: 150px; height: 100px" :src="waste.fileUrl" fit="cover" />

                    <!-- 垃圾类型选择 -->
                    <el-space direction="vertical" alignment="start" :size="10">
                      <el-space>
                        <el-select filterable v-model="waste.typeId" placeholder="请选择垃圾类型" style="width: 200px"
                          disabled>
                          <el-option v-for="item in wasteTypesOptions" :key="item.id" :label="item.typeName"
                            :value="item.id" />
                        </el-select>
                        <el-input-number v-model="waste.weight" :precision="2" :step="0.1" placeholder=""
                          style="width: 200px" disabled>
                          <template #suffix>千克(kg)</template>
                        </el-input-number>
                      </el-space>
                      <el-space>
                        回收收益:
                        <el-text style="padding-left:10px">
                          {{ waste.actualPrice ? `${waste.actualPrice}元` : '待计算' }}
                        </el-text>
                      </el-space>
                    </el-space>
                  </el-space>
                </div>
              </el-space>
            </el-scrollbar>
          </div>
        </el-form-item>
        <el-form-item label="回收地址" prop="address">
          <el-cascader size="large" :options="pcaTextArr" v-model="formData.area" disabled></el-cascader>
          <el-input v-model="formData.address" placeholder="详细地址" style="margin-left: 10px; height: 40px; width: 300px"
            disabled></el-input>
        </el-form-item>
        <el-form-item label="预约时间" prop="recycleTime">
          <el-date-picker v-model="formData.recycleTime" type="datetime" placeholder="预约时间" format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss" disabled></el-date-picker>
        </el-form-item>
        <el-form-item label="联系方式" prop="mobile">
          <el-input v-model="formData.mobile" placeholder="联系方式" style="width: 200px" disabled />
        </el-form-item>
        <el-form-item label="预期收益" prop="expectReturn"
          v-if="formData.status && formData.status != '0' && formData.status != '1'">
          <el-input-number v-model="formData.expectReturn" :precision="2" :step="0.1" placeholder="期望收益"
            style="width: 200px" disabled>
            <template #suffix>元</template>
          </el-input-number>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="formData.remark" placeholder="备注" type="textarea" :autosize="{ minRows: 2, maxRows: 4 }"
            resize="none" disabled />
        </el-form-item>
      </el-form>
      <!--审核表单-->
      <el-form ref="auditFormRef" :model="auditRecycleReq" label-width="100px" :rules="auditRules">
        <el-form-item label="回收人员" v-if="auditRecycleReq.auditStatus == '0' && formData.status == '0'" prop="courierId">
          <el-select v-model="auditRecycleReq.courierId" placeholder="请选择回收人员" style="width:250px">
            <el-option v-for="item in orgWorkers" :value="item.value" :label="item.label"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="取消原因" v-if="formData.status == '5'" prop="cancelReason">
          <el-input disabled v-model="formData.cancelReason" placeholder="取消原因" type="textarea"
            :autosize="{ minRows: 2, maxRows: 4 }" resize="none" />
        </el-form-item>
        <el-form-item label="处理操作员" v-if="auditRecycleReq.auditStatus == '0' && formData.status == '2'"
          prop="operatorId">
          <el-select v-model="auditRecycleReq.operatorId" placeholder="请选择操作员" style="width:250px">
            <el-option v-for="item in orgWorkers" :value="item.value" :label="item.label"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="审核状态" prop="auditStatus"
          v-if="(dialogType == 'info' && (formData.status == '1' || formData.status == '3')) || dialogType == 'audit'">
          <el-select v-model="auditRecycleReq.auditStatus" style="width:150px" v-if="dialogType == 'audit'">
            <el-option label="通过" value="0" />
            <el-option label="驳回" value="1" />
          </el-select>
          <span v-else>{{ getAuditResult(formData.status) }}</span>
        </el-form-item>
        <el-form-item label="驳回原因" v-if="auditRecycleReq.auditStatus == '1' || formData.status == '4'"
          prop="rejectReason">
          <el-input :disabled="dialogType == 'info'" v-model="auditRecycleReq.rejectReason" placeholder="驳回原因"
            type="textarea" :autosize="{ minRows: 2, maxRows: 4 }" resize="none" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div style="display: flex;justify-content: center;">
          <el-button v-if="dialogType == 'audit'" @click="handleCloseDialog()">取消</el-button>
          <el-button v-if="dialogType == 'audit'" @click="handleSubmit(formData.id)" type="primary">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
  <!--历史处理记录弹框-->
  <HistoryRecordList ref="historyRecordListRef"></HistoryRecordList>
</template>

<script setup lang="ts">
import { Edit, Refresh } from "@element-plus/icons-vue";

defineOptions({
  name: "RequestManger",
  inheritAttrs: false,
});

import HistoryRecordList from "@/components/HistoryRecordList/index.vue";
import RecycleRequestAPI, { RecycleQueryParams, WasteItem } from "@/api/system/recycle-request";
import RequestManagerAPI, { auditRequestDTO } from '@/api/system/recycle-manager'
import { RecycleStatusOptions } from "@/enums/RecycleStatusEnum";
import { pcaTextArr } from "element-china-area-data";

const queryFormRef = ref();
const dataFormRef = ref();

const loading = ref(false);
const removeIds = ref<number[]>([]);
const total = ref(0);

const queryParams = reactive<RecycleQueryParams>({
  pageNum: 1,
  pageSize: 10,
});

// 回收请求主表格数据
const pageData = ref([]);

// 弹窗
const dialog = reactive({
  title: "",
  visible: false,
});

// 回收请求主表单数据
const formData = reactive({
  id: "",
  userId: "",
  orgId: "",
  area: [], //包含省市区
  address: "",
  recycleTime: "",
  mobile: "",
  expectReturn: 0.0,
  remark: "",
  status: "",
  rejectReason: "",
  cancelReason: "",
  createTime: "",
  wasteList: [] as WasteItem[], // 指定数组类型
});

//审核请求
const auditFormRef = ref()
const auditRecycleReq = reactive<auditRequestDTO>({
  requestId: "",
  auditStatus: "",
  courierId: "",
  operatorId: "",
  rejectReason: "",
});

// 表单校验规则
const rules = reactive({
  id: [{ required: true, message: "请输入回收请求主表", trigger: "blur" }],
});

// 审核表单校验规则
const auditRules = reactive({
  auditStatus: [{
    required: true,
    message: '请选择审核结果',
    trigger: 'change'
  }],
  courierId: [{
    required: true,
    message: '请选择回收人员',
    trigger: 'change',
    validator: (rule, value, callback) => {
      if (auditRecycleReq.auditStatus == '0' && formData.status == '0' && !value) {
        callback(new Error('回收人员必须选择'))
      } else {
        callback()
      }
    }
  }],
  operatorId: [{
    required: true,
    message: '请选择处理操作员',
    trigger: 'change',
    validator: (rule, value, callback) => {
      if (auditRecycleReq.auditStatus == '0' && formData.status == '2' && !value) {
        callback(new Error('处理操作员必须选择'))
      } else {
        callback()
      }
    }
  }],
  rejectReason: [{
    required: true,
    message: '驳回原因不能为空',
    trigger: 'blur',
  }, {
    min: 5,
    max: 200,
    message: '长度在5到200个字符之间',
    trigger: 'blur'
  }]
});
const recycleTimeRange = ref([])

/** 重置回收请求主查询 */
function handleResetQuery() {
  queryFormRef.value!.resetFields();
  queryParams.pageNum = 1;
  queryParams.minExpectReturn = undefined;
  queryParams.maxExpectReturn = undefined;
  recycleTimeRange.value = [];
  handleQuery();
}


/** 打开回收请求主弹窗 */
const wasteTypesOptions = ref();
//查询隶属本机构的回收人员列表
const orgWorkers = ref([])

const dialogType = ref("")
async function handleOpenDialog(type: string, id?: number) {
  if (id) {
    if (type == 'audit') {
      dialog.title = "审核申请";
    } else if (type == 'info') {
      dialog.title = "详情";
    }
    //审核/详情
    dialogType.value = type;
    wasteTypesOptions.value = await RecycleRequestAPI.getAllWasteTypes();
    //查询隶属本机构的回收人员
    orgWorkers.value = await RequestManagerAPI.getOrgWorkers();
    //查询回写
    RecycleRequestAPI.getRecycleRequestForm(id).then((data) => {
      Object.assign(formData, data);
    });
  }
  dialog.visible = true;

}

/** 提交回收请求主表单 */
function handleSubmit(id?: string) {
  auditFormRef.value.validate((valid: any) => {
    if (valid) {
      auditRecycleReq.requestId = id;
      RequestManagerAPI.auditRecycleRequest(auditRecycleReq).then((data) => {
        if (data) {
          ElMessage.success("审核成功");
        } else {
          ElMessage.error("审核失败");
        }
        handleCloseDialog();
      })
    }
  });
}

/** 关闭回收请求主弹窗 */
function handleCloseDialog() {
  dialog.visible = false;
  dataFormRef.value.resetFields();
  dataFormRef.value.clearValidate();
  formData.id = "";

  auditRecycleReq.requestId = undefined;
  auditRecycleReq.auditStatus = "";
  auditRecycleReq.courierId = "";
  auditRecycleReq.rejectReason = "";
  auditRecycleReq.operatorId = "";

  auditFormRef.value.clearValidate();

  dialogType.value = ""
  handleQuery();
}
/**
 * 拼凑回收地址
 */
const assembleAddress = (row: any) => {
  if (row) {
    if (row.area) {
      return row.area.join("") + row.address;
    }
  }
};

/** 分页查询回收请求主 */
function handleQuery() {
  loading.value = true;
  if (recycleTimeRange.value.length) {
    if (recycleTimeRange.value.length == 2) {
      queryParams.recycleTimeStart = recycleTimeRange.value[0];
      queryParams.recycleTimeEnd = recycleTimeRange.value[1];
    } else {
      queryParams.recycleTimeStart = undefined;
      queryParams.recycleTimeEnd = undefined;
    }
  }
  RequestManagerAPI.getRecycleRequestPageOrg(queryParams)
    .then((data) => {
      pageData.value = data.list;
      total.value = data.total;
    })
    .finally(() => {
      loading.value = false;
    });
}
//判断是否通过
const getAuditResult = (status?: string) => {
  if (status == '1' || status == '3') {
    return '通过'
  } else if (status == '4') {
    auditRecycleReq.auditStatus = '1'
    return '驳回'
  }
}

/**
 * 历史处理记录
 */
const historyRecordListRef = ref(null)
const openHistoryRecord = (requestId: any) => {
  historyRecordListRef.value?.openHistoryDialog(requestId);
};
onMounted(() => {
  handleQuery();
});
</script>
